<?php

namespace app\modules\api\controllers;

use Yii;
use yii\web\Controller;
use common\models\Tools;
use app\components\FileUpload;

/**
 * Default controller for the `api` module
 */
class UploadController extends Controller
{
    public $enableCsrfValidation = false;
    //上传图片
    public function actionImg(){
        $type = $_FILES["file"]["type"];
        $size = $_FILES["file"]["size"];
        if($size > 10*1024*1024){//最大上传10M的图片
            $data['success'] = 0;
            $data['msg'] = "文件过大，请先压缩一下";
            Tools::outputjson($data);
        }
        if ($type != "image/gif" && $type != "image/jpeg" && $type != "image/pjpeg"){
            $data['success'] = 0;
            $data['msg'] = "格式不对，请上传正常格式的图片";
            Tools::outputjson($data);
        }
        
        if (!is_null($_FILES["file"])){
            $tmpName = $_FILES["file"]["tmp_name"];
            $fileName = $_FILES["file"]["name"];
            $extName = substr($fileName, strlen($fileName) - 3);
            $imgroot = rand(1, 9999);
            $path = Yii::$app->params['userauth'] .'/'. date('Y-m-d',time()).'/'.$imgroot;
            $path = $path .'/';

            //目录不存在的话，创建一个
            FileUpload::mkDirIfNotExist($path);

            //要保存到服务器上的文件名
            $result = $path . md5_file($tmpName) . "." . $extName;

            //上传文件，确保文件唯一性
            if (!file_exists($result)) {
                move_uploaded_file($tmpName, $result);
            }
            //去掉前面的".",保存到数据库中的信息
            $result = substr($result, 1, strlen($result));
            $data['success'] = 1;
            $data['url'] = $result;
            Tools::outputjson($data);
        }
    }
}